package com.bdqn.config;

import org.apache.shiro.web.filter.authc.AnonymousFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 放行过滤器，重写AnonymousFilter，实现login的跨域
 * 以及在shiro过滤url链中被标记为 anon 的跨域
 */
public class AnonFilter extends AnonymousFilter {

    public AnonFilter(){
        super();
    }


    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue){
        //跨域
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 除去login外其他url请求，跨域时因为携带请求头
        // 会首先发送一个 option请求，这里我们给 option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.onPreHandle(request, response,mappedValue);
    }

}
